package dai.samples.rabbit.errhandler.direct;

import com.rabbitmq.client.Channel;
import dai.samples.rabbit.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * 消息监听
 * @author daify
 * @date 2019-07-18 17:52
 **/
@Component
@Slf4j
public class DirectReceiver {

    /**
     * queues是指要监听的队列的名字
     * @param user
     */
    @RabbitListener(queues = DirectConfig.DIRECT_QUEUE1,
    // 注意此类为spring容器中的bean名称
    errorHandler = "myReceiverListenerErrorHandler",
    returnExceptions = "false")
    public void receiveDirect1(User user, Channel channel, Message message) {
        log.info("【receiveDirect1监听到消息】" + user);
        try {
            //告诉服务器收到这条消息 无需再发了 否则消息服务器以为这条消息没处理掉 后续还会在发
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("receiver success");
        } catch (IOException e) {
            e.printStackTrace();
            //丢弃这条消息
            log.info("receiver fail");
        }
        throw new RuntimeException("业务异常");
    }

    /**
     * queues是指要监听的队列的名字
     * @param user
     */
    @RabbitListener(queues = DirectConfig.DIRECT_QUEUE2,
            // 注意此类为spring容器中的bean名称
            errorHandler = "myReceiverListenerErrorHandler",
            returnExceptions = "false")
    public void receiveDirect2(User user,Channel channel, Message message)
            throws UnsupportedEncodingException {
        log.info("【receiveDirect2监听到消息】" + user);
        String s = new String(message.getBody(),"UTF-8");
        log.info(s);
        try {
            // 注意此时因为已经关闭了手动确认，所以下面代码可以不使用
            // 告诉服务器收到这条消息 无需再发了 否则消息服务器以为这条消息没处理掉 后续还会在发
            // channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            System.out.println("receiver success");
        } catch (Exception e) {
            e.printStackTrace();
            //丢弃这条消息
            System.out.println("receiver fail");
        }
    }
}